import socket
import threading
import time

class UDPServer:
    def __init__(self, host='0.0.0.0', port=12345, buffer_size=1024):
        self.host = host
        self.port = port
        self.buffer_size = buffer_size
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.server_socket.bind((self.host, self.port))
        self.is_running = False

    def start(self):
        self.is_running = True
        threading.Thread(target=self._listen, daemon=True).start()
        print(f"UDP server started on {self.host}:{self.port}")

    def stop(self):
        self.is_running = False
        self.server_socket.close()
        print("UDP server stopped")

    def _listen(self):
        while self.is_running:
            try:
                data, addr = self.server_socket.recvfrom(self.buffer_size)
                threading.Thread(target=self._handle_message, args=(data, addr), daemon=True).start()
            except socket.error as e:
                if self.is_running:
                    print(f"Socket error: {e}")

    def _handle_message(self, data, addr):
        rev = data.decode('utf-8')
        if rev == "get_now_time":
            current_time = time.localtime()
            time_str = "{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(
                current_time.tm_year, current_time.tm_mon, current_time.tm_mday,
                current_time.tm_hour, current_time.tm_min, current_time.tm_sec
            )
            self.server_socket.sendto(time_str.encode('utf-8'), addr)
        print(f"Received message from {addr}: {data.decode('utf-8')}")
        # 这里可以添加更多的处理逻辑

if __name__ == "__main__":
    udp_server = UDPServer(port=12345)
    try:
        udp_server.start()
        while True:
            pass  # 保持主线程运行，或者使用其他方式保持程序运行
    except KeyboardInterrupt:
        udp_server.stop()
